package com.shareniu.ch4;

import com.shareniu.BaseTest;
import org.drools.compiler.kie.builder.impl.ClasspathKieProject;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.drools.compiler.kie.builder.impl.KieContainerImpl;
import org.drools.compiler.kie.builder.impl.KieRepositoryImpl;
import org.drools.compiler.kproject.models.KieBaseModelImpl;
import org.drools.compiler.kproject.models.KieSessionModelImpl;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieSessionModel;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

/**
 *     //可以直接根据ksession的名称获取kieProject.getKieSessionModel("stateless-rules1");
 *     也可以通过KieSessionModelImpl找到KieBaseModelImpl
 *      可以通过KieBaseModelImpl找到KieSessionModelImpl。
 */
public class KieProjectSearchSessionTest extends BaseTest {
    @Test
    public void testFactHandler() {
        KieServices kieServices = KieServices.get();

        KieRepositoryImpl repository = (KieRepositoryImpl) kieServices.getRepository();
        System.out.println("repository:"+repository);
        ReleaseId defaultReleaseId = repository.getDefaultReleaseId();
        System.out.println("defaultReleaseId:"+defaultReleaseId);
        KieContainerImpl kieContainer = (KieContainerImpl) kieServices.getKieClasspathContainer();
        System.out.println("kieContainer######################:"+kieContainer);
        KieBaseModelImpl kieBaseModel1 = (KieBaseModelImpl) kieContainer.getKieBaseModel("stateless-rules");
        Map<String, KieSessionModel> kieSessionModels = kieBaseModel1.getKieSessionModels();
        Set<Map.Entry<String, KieSessionModel>> entries = kieSessionModels.entrySet();
        for(Map.Entry<String, KieSessionModel> entry :entries){
            String key = entry.getKey();
            KieSessionModel value = entry.getValue();
            System.out.println("通过KieSessionModel模型获取Session"+value.getName());

        }
        ClasspathKieProject kieProject = (ClasspathKieProject) kieContainer.getKieProject();
        InternalKieModule rules = kieProject.getKieModuleForKBase("rules");
        KieSessionModelImpl kieSessionModel = (KieSessionModelImpl) kieProject.getKieSessionModel("stateless-rules1");
        System.out.println("kieSessionModel,"+kieSessionModel);
        System.out.println(kieSessionModel.getName()+","+kieSessionModel.getType());

        KieBaseModelImpl kieBaseModel = kieSessionModel.getKieBaseModel();
        System.out.println("kieBaseModel:"+kieBaseModel.getName());
        System.out.println("getPackages:"+kieBaseModel.getPackages());
        InternalKieModule kieModuleForKBase = kieProject.getKieModuleForKBase("stateless-rules");

    }
}
